import type { MemberObj } from '@/types';
import { http } from '@/utils/request';
import { defineStore } from 'pinia';
import router from '@/router';
import { message } from '@/components/XtxUI';
import { useCartStore } from './cart';

export const useMemberStore = defineStore('member', {
  persist: {
    // 修改存储中使用的键名称，默认为当前 Store的 id
    key: 'member',
    // 按需持久化 默认全部持久化
    paths: ['pofile'],
  },
  state: () => {
    return {
      pofile: {} as MemberObj,
    };
  },
  getters: {
    isLogin(): boolean {
      return Boolean(this.pofile.token);
    },
  },
  actions: {
    // 第三方登录绑定
    async loginSocialBind(data: object) {
      const res = await http<MemberObj>('POST', '/login/social/bind', data);
      this.pofile = res.data.result;
      // 成功后得回调
      this.loginSccess();
    },
    // 获取验证码
    async sendCode(data: object) {
      await http('GET', '/login/social/code', data);
    },
    // 直接qq登录
    async loginQQUnionId(data: object) {
      const res = await http<MemberObj>('POST', '/login/social', data);
      this.pofile = res.data.result;
      this.loginSccess();
    },
    // 退出登录
    outLogin() {
      this.pofile = {} as MemberObj;
      message({ type: 'success', text: '您已退出登录' });
      // 退出登录清空购物车数据
      const cart = useCartStore();
      cart.clearCart();
    },
    // 登录成功后的操作
    loginSccess() {
      router.push('/');
      message({ type: 'success', text: '登录成功' });
      const { target } = router.currentRoute.value.query;
      router.push(target as string);
    },
    async login(data: object) {
      const res = await http<MemberObj>('post', '/login', data);
      this.pofile = res.data.result;
      const cart = useCartStore();
      cart.mergeLocalCart();
      // 登录成功后的操作
      this.loginSccess();
    },
  },
});
